require 'digest/sha1'
class Account < ActiveRecord::Base
  has_one :user, :dependent => :destroy


  ColumnNames = { :login => '登录名', :email => '邮箱', :password => '密码',:password_confirmation => '确认密码' }

  def self.human_attribute_name(attribute_key_name)
    human_attribute_names =  self::ColumnNames
    human_attribute_names[attribute_key_name.to_sym] || attribute_key_name.humanize
  end

  #所有字段的最大长度和最小长度
  LOGIN_MIN_LENGTH = 5
  LOGIN_MAX_LENGTH = 20
  PASSWORD_MIN_LENGTH = 6
  PASSWORD_MAX_LENGTH = 16
  EMAIL_MIN_LENGTH = 3
  EMAIL_MAX_LENGTH = 30
  LOGIN_RANGE = LOGIN_MIN_LENGTH..LOGIN_MAX_LENGTH
  PASSWORD_RANGE = PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH
  EMAIL_RANGE = EMAIL_MIN_LENGTH..EMAIL_MAX_LENGTH

  # Virtual attribute for the unencrypted password
  attr_accessor :password, :password_confirmation    # 不需要保存明文密码到数据库

  validates_presence_of     :login, :email, :message => "不能为空"
  validates_presence_of     :password, :message => "不能为空",    :if => :password_need?
  validates_presence_of     :password_confirmation, :message => "不能为空", :if => :password_required?
  validates_length_of       :password, :within => PASSWORD_RANGE, :if => :password_required?, :message =>"长度应为#{PASSWORD_MIN_LENGTH}到#{PASSWORD_MAX_LENGTH}之间"
  validates_confirmation_of :password, :if => :password_required?, :message => "确认密码与新密码不匹配"
  validates_length_of       :login,    :within => LOGIN_RANGE, :message =>"长度应为#{LOGIN_MIN_LENGTH}到#{LOGIN_MAX_LENGTH}之间", :if => Proc.new { |u| !u.login.blank? }
  validates_length_of       :email,    :within => EMAIL_RANGE, :message =>"长度应为#{EMAIL_MIN_LENGTH}到#{EMAIL_MAX_LENGTH}之间", :if => Proc.new { |u| !u.email.blank? }
  validates_uniqueness_of   :login, :email, :case_sensitive => false, :message => "已经存在", :if => Proc.new { |u| !u.email.blank? and !u.login.blank? }
  validates_format_of        :login,
    :with =>  /^[A-Z]+[A-Z0-9]*$/i,
    :message  =>  "只能包含字母和数字,并且只能为字母打头", :if => Proc.new { |u| !u.login.blank? }
  validates_format_of        :email,
    :with =>  /^[A-Z0-9._%-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i,
    :message  =>  "请输入一个有效的email地址", :if => Proc.new { |u| !u.email.blank? }
  before_save :encrypt_password     # 为密码加密
  
  # prevents a user from submitting a crafted form that bypasses activation
  # anything else you want your user to change should be added here.
  attr_accessible :login, :email, :password, :password_confirmation

  # Authenticates a user by their login name and unencrypted password.  Returns the user or nil.
  def self.authenticate(login, password)
    u = find_by_login(login) # need to get the salt
    u && u.authenticated?(password) ? u : nil
  end

  # Encrypts some data with the salt.
  def self.encrypt(password, salt)
    Digest::SHA1.hexdigest("--#{salt}--#{password}--")
  end

  # Encrypts the password with the user salt
  def encrypt(password)
    self.class.encrypt(password, salt)
  end

  def authenticated?(password)
    crypted_password == encrypt(password)
  end

  def remember_token?
    remember_token_expires_at && Time.now.utc < remember_token_expires_at 
  end

  # These create and unset the fields required for remembering users between browser closes
  def remember_me
    remember_me_for 2.weeks
  end

  def remember_me_for(time)
    remember_me_until time.from_now.utc
  end

  def remember_me_until(time)
    self.remember_token_expires_at = time
    self.remember_token            = encrypt("#{email}--#{remember_token_expires_at}")
    save(false)
  end

  def forget_me
    self.remember_token_expires_at = nil
    self.remember_token            = nil
    save(false)
  end

  # Returns true if the user has just been activated.
  def recently_activated?
    @activated
  end

  #
  #   valid login was exist
  #
  def self.valid_login_exist?(login_name)
    return false if Account.find_by_login(login_name).blank?
    return true
  rescue
    return true
  end

  #
  #   valid email was exist
  #
  def self.valid_email_exist?(email)
    begin
      @account = Account.find_by_email email
    rescue
      return true
    end
    if @account.blank?
      return false
    else
      return true
    end
  end

  protected
  # before filter
  def encrypt_password
    return if password.blank?
    self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
    self.crypted_password = encrypt(password)
  end
      
  def password_required?
    crypted_password.blank? || !password.blank?
  end

  def password_required?    # 当password不为空的时候需要校验的项目
    crypted_password.blank? || !password.blank?
  end

  def password_need?    # 当修改密码时,如果提交为空则此项为真；其余修改时此项为假，则不要校验密码
    crypted_password.blank? || password == ""
  end
    
end
